package org.testis.communicationmodule.services;

import org.testis.communication.client.AtofTcpClient;
import org.testis.communication.data.CommunicationModuleDataObject;
import org.testis.logging.AtofLogLevel;
import org.testis.logging.LogSenderService;
import org.testis.services.AtofModuleAction;
import org.testis.services.AtofModuleService;

/**
 * A class to define an tcp client action for
 * Communication module
 * @author nurhat
 */
public class TcpClientAction extends AtofModuleAction {

    /**
     * Function connects to given host and send and verify a string.
     * by using AtofTcpClient
     * @param request
     * @return
     */
    @Override
    public boolean operateRequest(AtofModuleService request) {
        CommunicationModuleDataObject dataObj =
                (CommunicationModuleDataObject) request.getDataObj();
        LogSenderService.putMessageOnQueue(
                "TcpClientAction",
                AtofLogLevel.INFO,
                "Starting to execute tcp client action ....with data:" + dataObj.toString() + "....",
                dataObj.getMessageId());
        String sendString = dataObj.getStringToSendAndVerify();
        if (sendString == null) {
            sendString = "DUMMY MESSAGE  SENT";
        }
        AtofTcpClient client = new AtofTcpClient(dataObj.getKeepAliveTime(),
                dataObj.getPort(),
                dataObj.getHost(),
                sendString);
        boolean result = false;
        String output = null;
        output = client.waitForServerMessage();
        if (output != null) {
            if (output.equals(sendString)) {
                result = true;
            }
        } else {
            output="N/A";
        }
        AtofLogLevel level = result ? AtofLogLevel.INFO : AtofLogLevel.ERROR;
        LogSenderService.putMessageOnQueue(
                "TcpClientAction",
                level,
                "TcpClientAction executed " + (result ? "" : "un") + "successfully..."+
                (result ? "" : " with error:" + client.getLastError())+
                ".Send message:" + sendString + " Recieved message:" + output,
                dataObj.getMessageId());
        return result;
    }
}
